package org.javaforever.cookieshop.controller;

import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;
import org.javaforever.cookieshop.domain.CustOrderBean;
import org.javaforever.cookieshop.domain.TypeBean;
import org.javaforever.cookieshop.domain.UserBean;
import org.javaforever.cookieshop.service.CustOrderService;
import org.javaforever.cookieshop.service.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;

@Controller
public class CustOrderCustController { 
	@Autowired
	protected CustOrderService oService;
	
	@Autowired
	protected TypeService typeService;
    
    @GetMapping("/order_submit")
    public String orderSubmit(HttpSession session, Model model) throws Exception{
        if(session.getAttribute("user")!=null) {
    	    List<TypeBean>typeList= typeService.listActiveTypes();
    	    model.addAttribute("typeList",typeList);
            return "order_submit";
        }else {
        	model.addAttribute("failMsg", "请登录后，再提交订单！");
    	    List<TypeBean>typeList= typeService.listActiveTypes();
    	    model.addAttribute("typeList",typeList);
        	return "user_login";
        }
    } 
    
    @PostMapping("/order_confirm")
    public String orderConfirm(HttpServletRequest request,HttpSession session,Model model) throws Exception{    	
    	CustOrderBean o = (CustOrderBean) session.getAttribute("order");
        try {
        	BeanUtils.copyProperties(o, request.getParameterMap());
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        o.setActive(true);
        o.setOrderDateTime(new Date());
        o.setStatus(2);
        o.setUser(((UserBean) session.getAttribute("user")).getId());
        oService.submitCustOrder(o);
        session.removeAttribute("order");
        model.addAttribute("msg", "订单支付成功！");
        return "order_success";
    }
    
    @GetMapping("/order_list")
    public String orderList(HttpSession session,Model model) throws Exception{
        UserBean u = (UserBean) session.getAttribute("user");
        if(u==null) return "index";
        CustOrderBean mo = new CustOrderBean();
        mo.setUser(u.getId());
        List<CustOrderBean> list = oService.searchCustOrdersByFields(mo);
        
	    List<TypeBean>typeList= typeService.listActiveTypes();
	    model.addAttribute("typeList",typeList);
        model.addAttribute("orderList", list);
        return "order_list";
     }
}
